import axios from "axios"
import { Message } from "element-ui"
import config from "./config"
import store from "@/store"

const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

const requests = axios.create({
  baseURL: baseUrl,
  timeout: 5000
})

requests.interceptors.request.use((config) => {
  // 在发送请求之前做些什么
  const token = store.state.user.token
  if (token) {
    config.headers.Authorization = token
  }
  return config;
}, (error) => {
  // 对请求错误做些什么
  return Promise.reject(error);
});

//响应拦截器
requests.interceptors.response.use(
  response => {
    //成功的回调函数：服务器响应数据回来以后，响应拦截器课以检测到，可以到一些事情
    const res = response.data
    if (res.code !== 200) {
      if (res.code === 10001) {
        Message({
          type: 'error',
          showClose: true,
          message: res.message
        })
      }
      if (res.code === 10002) {
        Message({
          type: 'error',
          showClose: true,
          message: res.message
        })
      }
      if (res.code === 10003) {
        store.commit('CLEAR')
        Message({
          type: 'error',
          showClose: true,
          message: res.message
        })
      }
      if (res.code === 10004) {
        Message({
          type: 'error',
          showClose: true,
          message: res.message
        })
      }
      if (res.code === 10005) {
        Message({
          type: 'error',
          showClose: true,
          message: res.message
        })
      }
      return res
    } else {
      return res
    }
  },
  error => {
    //响应失败的回调函数
    Message({
      type: 'warning',
      showClose: true,
      message: '连接超时'
    })
    return Promise.reject(error)
  });

export default requests
